package com.example.hotHub.service.impl;


import com.example.hotHub.model.NormalHotSearch;
import com.example.hotHub.service.HaokanHotPointService;
import com.example.hotHub.utils.SimpleMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HaokanHotPointServiceImpl implements HaokanHotPointService {

    @SneakyThrows
    private List<SimpleMap> getPage(Integer pageNo) {
        String target = "https://haokan.baidu.com/videoui/page/pc/toplist?type=hotvideo&sfrom=haokan_web_banner&pageSize=20&format=json&page=" + pageNo;
        Document document = Jsoup.connect(target).get();
        StringBuffer text = new StringBuffer(document.body().getElementById("_page_data").html().replace("window.__PRELOADED_STATE__ =", ""));
        text.setCharAt(text.length() - 1, ' ');
//        System.out.println(text);
        SimpleMap response = SimpleMap.parse(text.toString(), SimpleMap.class);

        if (response.getInt("total_page") < pageNo) {
            return Collections.emptyList();
        }

        return response.getList("video", SimpleMap.class);

    }

    @SneakyThrows
    @Override
    public List<NormalHotSearch> getHotPointList() {

        int pageNo = 1;
        List<SimpleMap> list = new ArrayList<>();

        while (true) {
            List<SimpleMap> page = getPage(pageNo++);
            if (page.isEmpty()) {
                break;
            }
            list.addAll(page);
        }

        List<NormalHotSearch> normalHotSearchList = new ArrayList<>();

        for (SimpleMap item : list) {
            String title = item.getString("title");
            String url = item.getString("pageUrl");
            String desc = item.getString("author");
            String imageUrl = item.getString("poster");
            Integer hotValue = item.getInt("hot");
            String videoUrl = item.getString("videoUrl");
            NormalHotSearch normalHotSearch = new NormalHotSearch()
                            .setTitle(title)
                            .setUrl(url)
                            .setDescribe(desc)
                            .setHotValue(hotValue)
                            .setImageUrl(imageUrl)
                            .setVideoUrl(videoUrl);
            normalHotSearchList.add(normalHotSearch);
        }

        normalHotSearchList = normalHotSearchList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

        log.debug("成功爬取好看视频热点: {}", normalHotSearchList);

        return normalHotSearchList;
    }
}
